<template>
  <view>
    <view class="container">
      <view class="pop-title">优惠券</view>
      <u-tabs :current="currentTab" :list="tabsList" @click="handleTabClick" :scrollable="false"
              lineColor="#ff9900"></u-tabs>
      <view class="pop-content">
        <scroll-view class="scroll-view" scroll-y>
          <view class="coupon__list">
            <view class="coupon__list__item" v-for="(item, index) in couponList('0')" :key="index">
              <view class="coupon__list__item__content">
                <view class="coupon__list__item__content__left active">
                  <view class="coupon__list__item__content__left__price" v-if="item.couponType === '3'">
                    <text>{{ item.couponDenomination }}</text>
                    折
                  </view>
                  <view class="coupon__list__item__content__left__price" v-else>
                    ¥
                    <text>{{ item.couponDenomination }}</text>
                  </view>
                  <view class="coupon__list__item__content__left__condition">
                    <text v-if="item.couponType === '1'||item.couponType === '3'">满{{
                        item.couponThreshold
                      }}可用
                    </text>
                    <text v-else-if="item.couponType === '2'">无门槛</text>
                  </view>
                </view>
                <view class="coupon__list__item__content__center">
                  <view class="coupon__list__item__content__center__name">
                    <text>{{ item.couponName }}</text>
                  </view>
                  <view class="coupon__list__item__content__center__validTime">
                    有效期：
                    <text>{{ item.activityStartTime }}至{{ item.activityEndTime }}</text>
                  </view>
                  <view class="coupon__list__item__content__center__desc">
                    <view class="coupon__list__item__content__center__desc__label">使用说明：</view>
                    <view class="coupon__list__item__content__center__desc__text"
                          v-html="item.couponInstruction"></view>
                    <view class="coupon__list__item__content__center__desc__detail"
                          @click.stop="handleShowCouponInstruction(item)">详情
                    </view>
                  </view>
                </view>
                <view class="coupon__list__item__content__right">
                  <u-checkbox-group @change="handleSelectCoupon(item,'0')" v-if="currentTab === 0">
                    <u-checkbox
                        :checked="singleCoupon.map(i=>i.couponRecordId).includes(item.couponRecordId)"
                        shape="circle"
                        activeColor="#FF9900"
                        :disabled="isCouponDisabled(item)">
                    </u-checkbox>
                  </u-checkbox-group>
                </view>
              </view>
            </view>
            <view v-if="currentTab === 0 && couponList('1').length">
              <view style="margin: 20rpx 0;font-size: 28rpx;color: #999;">可叠加</view>
              <view class="coupon__list__item"
                    v-for="(item, index) in couponList('1')" :key="index">
                <view class="coupon__list__item__content">
                  <view class="coupon__list__item__content__left active">
                    <view class="coupon__list__item__content__left__price" v-if="item.couponType === '3'">
                      <text>{{ item.couponDenomination }}</text>
                      折
                    </view>
                    <view class="coupon__list__item__content__left__price" v-else>
                      ¥
                      <text>{{ item.couponDenomination }}</text>
                    </view>
                    <view class="coupon__list__item__content__left__condition">
                      <text v-if="item.couponType === '1'||item.couponType === '3'">满{{
                          item.couponThreshold
                        }}可用
                      </text>
                      <text v-else-if="item.couponType === '2'">无门槛</text>
                    </view>
                  </view>
                  <view class="coupon__list__item__content__center">
                    <view class="coupon__list__item__content__center__name">
                      <text>{{ item.couponName }}</text>
                    </view>
                    <view class="coupon__list__item__content__center__validTime">
                      有效期：
                      <text>{{ item.activityStartTime }}至{{ item.activityEndTime }}</text>
                    </view>
                    <view class="coupon__list__item__content__center__desc">
                      <view class="coupon__list__item__content__center__desc__label">使用说明：</view>
                      <view class="coupon__list__item__content__center__desc__text"
                            v-html="item.couponInstruction"></view>
                      <view class="coupon__list__item__content__center__desc__detail"
                            @click="handleShowCouponInstruction(item)">详情
                      </view>
                    </view>
                  </view>
                  <view class="coupon__list__item__content__right">
                    <u-checkbox-group @change="handleSelectCoupon(item,'1')" v-if="currentTab === 0">
                      <u-checkbox shape="circle" activeColor="#FF9900"
                                  :checked="multiCoupon.map(i=>i.couponRecordId).includes(item.couponRecordId)"
                                  :disabled="isCouponDisabled(item)"></u-checkbox>
                    </u-checkbox-group>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view
              v-if="(currentTab === 0 && useableCouponList.length === 0) || (currentTab === 1 && unUseableCouponList.length === 0)">
            <view style="color: #999;text-align: center;margin-top: 50rpx;">暂无优惠券</view>
          </view>
        </scroll-view>
      </view>
      <view class="pop-footer">
        <view class="pop-footer__price">
          <view class="pop-footer__price__item">
            <text>原价:</text>
            <text style="color: #999;">¥{{ params.couponThreshold }}</text>
          </view>
          <view class="pop-footer__price__item">
            <text>优惠:</text>
            <text style="color: #FF9900;">¥{{ currentCouponPrice }}</text>
          </view>
          <view class="pop-footer__price__item">
            <text>合计:</text>
            <text style="color: #FF9900;">¥{{ currentHousePrice }}</text>
          </view>

        </view>
        <view class="pop-footer__button">
          <button class="pop-footer__button__item" @click.stop="handleNoUseCoupon">不使用优惠券</button>
          <button class="pop-footer__button__item active" @click.stop="handleUseCoupon">确定</button>
        </view>
      </view>
    </view>
    <!--   使用说明弹窗   -->
    <hxk-dialog ref="couponInstructionDialog">
      <view class="dialog__content" slot="content">
        <view class="dialog__content__desc" v-html="couponInstructionDialogData.couponInstruction"></view>
      </view>
    </hxk-dialog>
  </view>
</template>
<script>
import {getCouponByHouseIdUseState} from "@/api/mine/coupon";

export default {
  name: "index",
  props: {
    params: {
      type: Object,
      default: () => ({})
    },
    // 选择的优惠券
    selectedCoupon: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      currentTab: 0,
      tabsList: [
        {
          name: '可用优惠券(0)',
          value: '0'
        },
        {
          name: '不可用优惠券(0)',
          value: '1'
        },
      ],
      //
      couponUseableParams: {
        houseId: '',
        useState: '', //优惠券使用状态(0:可使用,1:不可使用)
        couponThreshold: null,
      },
      // 可用优惠券列表
      useableCouponList: [],
      // 不可用优惠券列表
      unUseableCouponList: [],
      // 说明数据
      couponInstructionDialogData: {},
      // 单选优惠券
      singleCoupon: [],
      // 多选优惠券
      multiCoupon: [],
      // 当前选择的优惠券
      currentSelectedCoupon: [],
      // 当前优惠券价格
      currentCouponPrice: 0,
    }
  },
  computed: {
    // 优惠券列表
    couponList: {
      get() {
        return (superpositionType) => {
          if (this.currentTab === 0) {
            if (superpositionType === '1') {
              return this.useableCouponList.filter(item => item.superpositionType === '1');
            } else {
              return this.useableCouponList.filter(item => item.superpositionType === '0');
            }
          } else {
            return this.unUseableCouponList;
          }

        }
      },
      set(val) {
      }
    },
    // 当前房费
    currentHousePrice: {
      get() {
        let housetotalPrice = this.params.couponThreshold; // 房屋总价
        this.currentSelectedCoupon.forEach(item => {
          // 优惠券类型为折扣券时
          if (item.couponType === '3') {
            housetotalPrice = (housetotalPrice * item.couponDenomination) / 10;
          } else {
            // 优惠券类型为减免券时
            housetotalPrice = housetotalPrice - item.couponDenomination;
          }
        })
        this.currentCouponPrice = (this.params.couponThreshold - housetotalPrice).toFixed(2);
        return Number(housetotalPrice.toFixed(2));
      },
      set(val) {
      }
    },
    // 判断优惠券是否可选（根据可用优惠券列表中做判断，则不存在不可用情况，不可用情况则在选择某个优惠券后，对余下的优惠券做限制）
    isCouponDisabled() {
      return (data) => {
        // 单选优惠券
        if (data.superpositionType === '0') {
          let singleCouponIds = this.singleCoupon.map(i => i.couponRecordId);
          // 当已选多选券时，判断限制禁用单选券
          if (this.multiCoupon.length > 0) {
            // 非已选的单选券的情况下
            if (!singleCouponIds.includes(data.couponRecordId)) {
              // 优惠券类型为折扣券时
              if (data.couponType === '3') {
              } else { // 优惠券类型为减免券时
                // 判断优惠券面额是否大于当前房费
                if (data.couponDenomination > this.currentHousePrice) return true;
              }
              // 判断优惠券门槛是否大于当前房费
              if (data.couponThreshold > this.currentHousePrice) return true;
            }
          } else { // 未选多选券时，判断禁用单选券
            // 优惠券类型为折扣券时
            if (data.couponType === '3') {

            } else {// 优惠券类型为减免券时couponType:1,2
              // 判断优惠券面额是否大于初始房费
              if (data.couponDenomination > this.params.couponThreshold) {
                return true;
              } else {
                return false;
              }
            }
          }
        }
        // 多选优惠券
        else {
          let multiCouponIds = this.multiCoupon.map(i => i.couponRecordId);
          //非已选的多选券的情况下
          if (!multiCouponIds.includes(data.couponRecordId)) {
            // 优惠券类型为折扣券时
            if (data.couponType === '3') {

            } else { // 优惠券类型为减免券时
              // 判断优惠券面额是否大于当前房费
              if (data.couponDenomination > this.currentHousePrice) return true;
            }
            // 判断优惠券门槛是否大于当前房费
            if (data.couponThreshold > this.currentHousePrice) return true;
          }
        }
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    // 初始化
    init() {
      this.currentTab = 0;
      this.getUseableCoupon('0');
      this.getUseableCoupon('1');
      this.currentSelectedCoupon = JSON.parse(JSON.stringify(this.selectedCoupon));
      this.singleCoupon = this.selectedCoupon.filter(item => item.superpositionType === '0');
      this.multiCoupon = this.selectedCoupon.filter(item => item.superpositionType === '1');
    },
    // 点击tab切换
    handleTabClick(item) {
      this.currentTab = item.index;
    },
    // 获取可用优惠券
    getUseableCoupon(useState = '1') {
      this.couponUseableParams.houseId = this.params.houseId;
      this.couponUseableParams.couponThreshold = this.params.couponThreshold;
      this.couponUseableParams.useState = useState;
      getCouponByHouseIdUseState(this.couponUseableParams).then(res => {
        if (useState === '0') {
          this.useableCouponList = res.rows;
          this.tabsList[0].name = `可用优惠券(${this.useableCouponList.length})`;
        } else {
          this.unUseableCouponList = res.rows;
          this.tabsList[1].name = `不可用优惠券(${this.unUseableCouponList.length})`;
        }
      })
    },
    // 显示使用说明
    handleShowCouponInstruction(item) {
      this.couponInstructionDialogData = item;
      this.$refs.couponInstructionDialog.confirm({
        title: '使用说明',
        showCancel: false,
        confirmText: '知道了'
      })
    },
    // 选择优惠券
    handleSelectCoupon(item, superpositionType) {
      if (superpositionType === '0') {
        if (this.singleCoupon.length && this.singleCoupon[0].couponRecordId === item.couponRecordId) {
          this.singleCoupon = [];
        } else {
          this.singleCoupon = [item];
        }
      } else if (superpositionType === '1') {
        let index = this.multiCoupon.findIndex(i => i.couponRecordId === item.couponRecordId)
        if (index !== -1) {
          this.multiCoupon.splice(index, 1)
        } else {
          this.multiCoupon.push(item)
        }
      }
      // 记录当前选择的优惠券（包含单选和多选）
      let currentSelectedIndex = this.currentSelectedCoupon.findIndex(i => i.couponRecordId === item.couponRecordId)
      if (currentSelectedIndex === -1) {
        if (superpositionType === '0') {
          this.currentSelectedCoupon = [...this.multiCoupon]
        }
        this.currentSelectedCoupon.push(item)
      } else {
        this.currentSelectedCoupon.splice(currentSelectedIndex, 1)
      }
      console.log('this.currentSelectedCoupon', this.currentSelectedCoupon)
      console.log('this.singleCoupon', this.singleCoupon)
      console.log('this.multiCoupon', this.multiCoupon)
    },
    // 使用优惠券
    handleUseCoupon() {
      // this.$emit('submit', [...this.singleCoupon, ...this.multiCoupon]);
      this.$emit('submit',[...this.currentSelectedCoupon])
      this.handleClose();
    },
    // 不使用优惠券
    handleNoUseCoupon() {
      this.$emit('submit', []);
      this.handleClose();
    },
    // 关闭
    handleClose() {
      this.$emit('close');
    }
  }
}
</script>

<style scoped lang="scss">

.container {
  width: 750rpx;
  //height: 1134rpx;
  background: #FFFFFF;
  border-radius: 20rpx 20rpx 0rpx 0rpx;

  .pop-title {
    font-family: PingFang SC, PingFang SC;
    font-weight: 800;
    font-size: 34rpx;
    color: #000000;
    text-align: center;
    font-style: normal;
    text-transform: none;
    margin: 40rpx 0 46rpx 0;
  }

  .pop-content {
    background: #F2F2F2;

    .scroll-view {
      height: 800rpx;
    }
  }

  .pop-footer {
    padding: 20rpx;

    .pop-footer__price {
      //display: flex;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-gap: 20rpx;
      margin-bottom: 20rpx;
    }

    .pop-footer__button {
      display: flex;

      .pop-footer__button__item {
        height: 73rpx;
        border-radius: 12rpx 12rpx 12rpx 12rpx;
        font-size: 30rpx;
        background-color: #FFFFFF;
        color: #000000;
        margin-right: 20rpx;
        flex: 1;

        &.active {
          color: #fff;
          background-color: #FF7950;
        }

        &:last-child {
          margin-right: 0;
        }

      }
    }
  }

}

.coupon__list {
  padding: 30rpx;

  .coupon__list__item {
    background-color: #fff;
    border-radius: 10rpx;
    margin-bottom: 10rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .coupon__list__item__content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx;

      .coupon__list__item__content__left {
        width: 25%;
        text-align: center;

        &.active {
          color: $hxk-primary-color;
        }

        .coupon__list__item__content__left__price {
          font-size: 20rpx;
          margin-bottom: 10rpx;

          text {
            font-size: 32rpx;
            font-weight: bold;
          }
        }

        .coupon__list__item__content__left__condition {
          font-size: 20rpx;
        }
      }

      .coupon__list__item__content__center {
        padding: 0 10rpx;
        border-left: 1rpx dashed #D7D7D7;
        width: 60%;

        .coupon__list__item__content__center__name {
          font-size: 28rpx;
          margin-bottom: 20rpx;
          font-weight: bold;
        }

        .coupon__list__item__content__center__validTime {
          font-size: 24rpx;
          margin-bottom: 20rpx;
        }

        .coupon__list__item__content__center__desc {
          font-size: 24rpx;
          line-height: 32rpx;
          text-align: justify;
          display: flex;

          .coupon__list__item__content__center__desc__label {
            white-space: nowrap;
          }

          .coupon__list__item__content__center__desc__text {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            overflow: hidden;
          }

          .coupon__list__item__content__center__desc__detail {
            color: #02BAF6;
            white-space: nowrap;
          }

        }
      }

      .coupon__list__item__content__right {
        width: 15%;
        text-align: center;

        .coupon__list__item__content__right__button {
          display: block;
          width: 100%;
          height: 50rpx;
          line-height: 50rpx;
          border-radius: 10rpx;
          background-color: $hxk-primary-color;;
          border: 1rpx solid $hxk-primary-color;
          color: #FFFFFF;
          font-size: 22rpx;

          &.active {
            border: 1rpx solid $hxk-primary-color;
            color: $hxk-primary-color;
            background-color: #fff;
          }
        }
      }
    }

  }
}
</style>